from random import randint

from django.shortcuts import render

# Create your views here.


from django.http import HttpResponse
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from libs.captcha.captcha import captcha
from libs.yuntongxun.sms import CCP
from verifications.serializers import RegisterSMSCodeSerializer

"""图片验证码"""


class RegisterImageCodeView(APIView):
    def get(self, request, image_code_id):
        # 创建图片验证码,包括图片内容和图片
        text, image = captcha.generate_captcha()
        # 通过redis保存图片验证码 (code设置中数据库的别名)
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_%s' % image_code_id, 60, text)
        # 将图片返回(图片是二进制数据,所以通过HttpResponse返回,并修改content_type为image)
        return HttpResponse(image, content_type='image/jpeg')


"""短信验证码"""


class RegisterSMSCodeView(GenericAPIView):
    serializer_class = RegisterSMSCodeSerializer

    def get(self, request, mobile):
        # 创建序列化器,定义text和image_code_id
        serializer = self.get_serializer(data=request.query_params)
        # 对数据进行校验
        serializer.is_valid(raise_exception=True)

        # 连接到数据库
        redis_conn = get_redis_connection('code')

        # 判断用户是否频繁获取
        if redis_conn.get('sms_flag_%s' % mobile):
            return Response(status=status.HTTP_429_TOO_MANY_REQUESTS)
        # 生成短信验证码
        sms_code = '%06d' % randint(0, 999999)

        # 将短信验证码保存到redis
        redis_conn.setex('sms_%s' % mobile, 5 * 60, sms_code)

        redis_conn.setex('sms_flag_%s' % mobile, 60, 1)

        # 发送短信
        # 6.将原先任务 改成 celery发送
        from celery_tasks.sms.tasks import send_sms
        send_sms.delay(mobile, sms_code)

        # 返回响应
        return Response({'message': 'ok'})
